const Printer = require('lighthouse/lighthouse-cli/printer');
const fs = require('fs-extra');
const Reporter = require('lighthouse/lighthouse-core/report/report-generator');

/**
 * 生成报告：lighthouse运行后返回性能测试结果是json格式，使用lighthouse官网的模板生成报告
 */
function generateHtmlReport(result) {
    try {
        return Reporter.generateReport(result, 'html')
    } catch (error) {
       console.log("生成lighthouse报告数据出错", error);
    }
}

async function printeHtmlReport(report, path, filename) {
    try {
        return await Printer.write(report, "html", `${path}/${filename}.html`);
    } catch (error) {
        console.log("输出lighthouse html报告出错", error);
    }
    
}

/**
 * 写入 report 文件
 * @param {*} file 文件名
 * @param {*} report 报告内容
 */
async function writeReport(file, report) {
    try {
        await fs.outputFile(file, report);
    } catch (error) {
        console.log("输出报告文件出错", error);
    }
}

module.exports = {
    generateHtmlReport,
    printeHtmlReport,
    writeReport
}

